#include <stdio.h>
#include <stdlib.h>

struct student {
    char num[10];
    char name[8];
    int score[3];
    float ave;
};

int main() {
    FILE *fp, *fp1;
    int i, t, n, j;
    struct student st[10], s;

    // 输入插入学生的相关信息
    printf("NO.: ");
    scanf("%s", s.num);
    printf("name: ");
    scanf("%s", s.name);
    printf("score1, score2, score3: ");
    scanf("%d, %d, %d", &s.score[0], &s.score[1], &s.score[2]);
    s.ave = (s.score[0] + s.score[1] + s.score[2]) / 3.0;

    // 从文件读数据
    if ((fp = fopen("d:\\stu_sort", "r")) == NULL) {
        printf("can not open file.");
        exit(0);
    }

    // 输出读取的文件内容
    printf("original data:\n");
    for (i = 0; fread(&st[i], sizeof(struct student), 1, fp) != 0; i++) {
        printf("\n%8s%8s", st[i].num, st[i].name);
        for (j = 0; j < 3; j++) {
            printf("%8d", st[i].score[j]);
        }
        printf("%10.2f", st[i].ave);
    }
    n = i;

    for (t = 0; st[t].ave > s.ave && t < n; t++); // 寻找插入点t

    // 向文件写数据
    printf("\nNow:\n");
    fp1 = fopen("d:\\sortl", "w");
    for (i = 0; i < t; i++) { // 写入插入结点前半部分
        fwrite(&st[i], sizeof(struct student), 1, fp1);
        printf("\n%8s%8s", st[i].num, st[i].name);
        for (j = 0; j < 3; j++) {
            printf("%8d", st[i].score[j]);
        }
        printf("%10.2f", st[i].ave);
    }

    fwrite(&s, sizeof(struct student), 1, fp1); // 写入插入的学生
    printf("\n%8s%8s%8d%8d%8d%10.2f", s.num, s.name, s.score[0], s.score[1], s.score[2], s.ave);

    for (i = t; i < n; i++) { // 写入插入结点后半部分
        fwrite(&st[i], sizeof(struct student), 1, fp1);
        printf("\n%8s%8s", st[i].num, st[i].name);
        for (j = 0; j < 3; j++) {
            printf("%8d", st[i].score[j]);
        }
        printf("%10.2f", st[i].ave);
    }

    printf("\n");
    fclose(fp);
    fclose(fp1);
    return 0;
}